package controller;

import java.util.List;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.activerecord.tx.Tx;

import model.Course;
import model.Student;
import model.Teacher;

/**
 * Created by BaiYunfei on 2017/6/14.
 */
public class CourseController extends BaseController {
    public void list(){
    	int role = getRole();
    	SqlPara sqlPara = null;
    	switch (role) {
		case 3:
			sqlPara = Db.getSqlPara("course.list");
			break;
		case 2:
			Teacher t = Teacher.dao.findByUserId(getUserId());
			sqlPara = Db.getSqlPara("course.listByTeacher", t.getStr("Teacher_ID"));
			break;
		case 1:
			Student stu = Student.dao.findByUserId(getUserId());
			sqlPara = Db.getSqlPara("course.listSelectable", stu.getStr("Student_ID"));
			break;
		default:
			break;
		}
        Page<Course> coursePage = Course.dao.paginate(getPageNumber(),getPageSize(),sqlPara);
        renderDataTable(coursePage);
    }

    @Before(Tx.class)
    public void save(){
        Course course = getModel(Course.class,"");
        if(Course.dao.findById(course.getStr("Course_ID")) != null){
            course.update();
        }else{
        	course.save();
        }
        setAttr("status","success");
        renderJson();
    }
    
    public void remove(){
    	String id = getPara("id");
    	Course.dao.deleteById(id);
    	renderJson();
    }
    
    public void addPage(){
    	if(isParaExists("id")){
    		String id = getPara("id");
    		Course course  = Course.dao.findById(id);
    		setAttr("course",course);
    	}
    	List<Teacher> teacherList = Teacher.dao.find("SELECT * FROM Teacher");
    	setAttr("teacherList", teacherList);
        render("course-add.html");
    }

    public void index(){
        render("course-list.html");
    }

}
